package cn.learn.shiro;

import cn.learn.domain.module.Module;
import cn.learn.domain.system.user.User;
import cn.learn.service.system.user.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;

public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override  //授权（获取当前认证用户的所有权限）
    //principalCollection：认证用户
    //AuthorizationInfo: 返回的认证用户具备的所有权限集合
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取该认证用户的所有具备权限
        User user =(User)principalCollection.getPrimaryPrincipal();
        List<Module> list = userService.findMenus(user);
        // 将所有的权限名放入set集合中
        HashSet set = new HashSet();
        for (Module module : list) {
            set.add(module.getName());
        }
        System.out.println(set);
        // 将set集合装入SimpleAuthorizationInfo对象返回
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(set);
        return info;
    }

    @Override // 认证（从数据库中获取安全数据）
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1 获取uptoken拿着账号名
        UsernamePasswordToken uptoken=(UsernamePasswordToken)authenticationToken;
        String email = uptoken.getUsername();
        //2 根据email从数据中获取安全数据user对象
        User user = userService.findByEmail(email);
        if(user!=null){
            // 调用密码比较器--调用密码比较器比较页面的密码和安全数据的密码是否一致
            //Object principal, Object credentials, String realmName
            // 参数1：安全数据 user对象
            // 参数2：安全数据的密码 user.getPassword()
            // 参数3：当前reaml的名称  this.getname()
            return new SimpleAuthenticationInfo(user,user.getPassword(),this.getName());
        }
        return null; // 抛异常
    }
}
